package service;

import java.util.List;
import java.util.Map;

import beans.Goods;
import beans.Info;
import beans.Shop;
import dao.DAO;

public class GoodService {
	private static final int PERPAGE = 15;
	DAO<Goods> dao = null;

	public GoodService() {
		dao = new DAO<>(Goods.class);
	}

	/**
	 * 获取所有商品
	 * 
	 * @param page
	 * @param id
	 * @return
	 */
	public Info<Goods> getGoods(String page, String id) {
		int startP = (Integer.parseInt(page) - 1) * PERPAGE; // 分页开始条数
		String hql = "from Goods where shop.id=" + id + " order by id desc ";
		return byHQL(hql, startP);
	}

	/**
	 * 根据姓名模糊查找商品
	 * 
	 * @param name
	 * @param page
	 * @param id
	 * @return
	 */
	public Info<Goods> getGoodsByName(String name, String page, String id) {
		int startP = (Integer.parseInt(page) - 1) * PERPAGE; // 分页开始条数
		String hql = "from Goods where shop.id=" + id + " and name like '%" + name + "%' order by id desc ";
		return byHQL(hql, startP);
	}

	/**
	 * 执行hql并将结果转换为Info类型
	 * 
	 * @param hql
	 * @param startP
	 * @return
	 */
	private Info<Goods> byHQL(String hql, int startP) {
		Map<Long, List<Goods>> goodMap = dao.getFromHQL(hql, startP, startP + PERPAGE);
		Info<Goods> info = new Info<>();
		info.count = goodMap.keySet().iterator().next();
		info.list = goodMap.values().iterator().next();
		return info;
	}

	/**
	 * 根据id查询商品信息
	 * 
	 * @param id
	 * @return
	 */
	public Goods getGoodsById(String id) {
		return dao.getById(Integer.parseInt(id));
	}

	/**
	 * 修改商品信息
	 * 
	 * @param id
	 * @param name
	 * @param price
	 * @param classify
	 * @param stock
	 * @param sales
	 * @param goodDescribe
	 * @param status
	 */
	public void alterGood(String id, String name, String price, String classify, String stock, String sales,
			String goodDescribe, String status) {
		String sql = "update Goods set name='" + name + "', price=" + price + ", classify='" + classify + "', stock="
				+ stock + ", sales=" + sales + ", goodDescribe='" + goodDescribe + "', status='" + status + "' where id="
				+ id;
		dao.updateSQL(sql);
	}

	/**
	 * 根据id删除商品信息
	 * @param id
	 */
	public void deleteById(String id) {
		dao.delById(Integer.parseInt(id));
	}
	/**
	 * 添加商品信息
	 * 
	 * @param sid
	 * @param name
	 * @param price
	 * @param classify
	 * @param stock
	 * @param sales
	 * @param goodDescribe
	 * @param status
	 */
	public void addGood(String sid, String name, String price, String classify, String stock, String sales,
			String goodDescribe, String status) {
		ShopService service = new ShopService();
		Shop shop = service.getShopById(sid);
		Goods good = new Goods(0, name, Double.parseDouble(price), classify, Integer.parseInt(stock), Integer.parseInt(sales), goodDescribe, status, shop);
		dao.add(good);
	}

}
